package controllers;

import java.util.List;

import controllers.CRUD.ObjectType;
import models.Organizacion;
import models.Rama;
import models.Rubro;
import models.Sector;
import models.Subrubro;
import play.db.Model;
import play.exceptions.TemplateNotFoundException;
import play.mvc.With;

@With(Secure.class)
@CRUD.For(value = Sector.class)
public class Sectores extends ArcadiaCRUD {
	
	public static void show(String id, Long selectedRama, Long selectedRubro) throws Exception {
        if (selectedRama!=null && selectedRubro!=null)
        	selectRubro(id, selectedRama.toString(), selectedRubro.toString());
        else if (selectedRama!=null)
        	selectRama(id, selectedRama.toString());
        else {
    		ObjectType type = ObjectType.get(getControllerClass());
            notFoundIfNull(type);
            Model object = type.findById(id);
            notFoundIfNull(object);
            List<Rama> ramas = Rama.find("sector = ?", object).fetch();
            try {
                render(type, object, ramas, selectedRama);
            } catch (TemplateNotFoundException e) {
                render("CRUD/show.html", type, object);
            }
        }
    }
	
	public static void selectRama(String id, String rama) throws Exception {
		ObjectType type = ObjectType.get(getControllerClass());
        notFoundIfNull(type);
        Model object = type.findById(id);
        notFoundIfNull(object);
        List<Rama> ramas = Rama.find("sector = ?", object).fetch();
        
        List<Rubro> rubros = Rubro.find("rama.id = ?", new Long(rama)).fetch();
        String selectedRama = rama;
        try {
            render("Sectores/show.html", object, ramas, rubros, selectedRama);
        } catch (TemplateNotFoundException e) {
            render("CRUD/show.html", type, object);
        }
	}
	public static void selectRubro(String id, String rama, String rubro) throws Exception {
		ObjectType type = ObjectType.get(getControllerClass());
        notFoundIfNull(type);
        Model object = type.findById(id);
        notFoundIfNull(object);
        List<Rama> ramas = Rama.find("sector = ?", object).fetch();
        List<Rubro> rubros = Rubro.find("rama.id = ?", new Long(rama)).fetch();
        List<Subrubros> subrubros = Subrubro.find("rubro.id = ?", new Long(rubro)).fetch();
        String selectedRama = rama;
        String selectedRubro = rubro;
        try {
            render("Sectores/show.html", object, ramas, rubros, subrubros, selectedRama, selectedRubro);
        } catch (TemplateNotFoundException e) {
            render("CRUD/show.html", type, object);
        }
	}
}
